package com.yhl.admin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author yhl
 * @create 2021-06-19 20:41
 */
@Controller
public class FileUploadController {

    @GetMapping("/form_layouts")
    public String form_layouts(){

        return "/form/form_layouts";
    }

    @PostMapping("/upload")
    public String fileUpload(@RequestParam("email") String email,
                             @RequestParam("userName") String userName,
                             @RequestPart("headerImg") MultipartFile headerImg,
                             @RequestPart("photos") MultipartFile[] photos) throws IOException {

        System.out.println("上传的文件是：email{}, userName{}, headerImg{}, photos{}" +
                email +";" +  userName +";" + headerImg.getSize() + ";"+ photos.length);

        //单个文件下载
        /*
         InputStream is = headerImg.getInputStream();
        FileOutputStream fos = new FileOutputStream("/E:\\文件上传\\"+ headerImg.getOriginalFilename());
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1){
            fos.write(buffer,0, len);
        }
         */

        if (!headerImg.isEmpty()){
            String fileName = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("/E:\\文件上传\\" + fileName));
        }


        //多个文件下载
        for (MultipartFile photo : photos) {
            if (!photo.isEmpty()){
                String fileName = photo.getOriginalFilename();
                photo.transferTo(new File("/E:\\文件上传\\" + fileName));
            }
        }

        return "main";
    }
}
